using B.S.RbacData.ErrorCode;
using ContentmanagementBaseWrite.API.Applications.Commands;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace ContentmanagementBaseWrite.API.Controllers
{
    /// <summary>
    /// 内容管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class CarouselController : ControllerBase
    {
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator _mediator;
        // <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<CarouselController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public CarouselController(IMediator mediator, ILogger<CarouselController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 新增轮播图
        /// </summary>
        /// <param name="command">轮播图信息</param>
        /// <returns>新增结果</returns>
        [HttpPost("add")]
        public async Task<ApiResult<int>> AddCarousel([FromBody] AddNewCarouselCommand command)
        {
            try
            {
                _logger.LogInformation("开始新增轮播图，标题：{Title}", command.CarouelChartTitle);

                var result = await _mediator.Send(command);

                _logger.LogInformation("轮播图新增成功，ID：{Id}", result.data);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "轮播图新增过程中发生异常，标题：{Title}", command.CarouelChartTitle);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"轮播图新增异常：{ex.Message}",
                    data = 0
                };
            }
        }

        /// <summary>
        /// 上传轮播图图片
        /// </summary>
        /// <param name="imageFile">图片文件</param>
        /// <param name="bucketName">存储桶名称（可选，默认为image）</param>
        /// <param name="prefix">文件前缀（可选，默认为carousel）</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload-image")]
        public async Task<ApiResult<string>> UploadCarouselImage(
             IFormFile imageFile,
            string bucketName = "image",
             string prefix = "carousel")
        {
            try
            {
                _logger.LogInformation("开始上传轮播图图片，文件名：{FileName}，存储桶：{BucketName}，前缀：{Prefix}",
                    imageFile?.FileName, bucketName, prefix);

                var command = new UploadImageCommand
                {
                    ImageFile = imageFile,
                    BucketName = bucketName,
                    Prefix = prefix,
                    GenerateUniqueName = true
                };

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("轮播图图片上传成功，URL：{ImageUrl}", result.data);
                }
                else
                {
                    _logger.LogWarning("轮播图图片上传失败，错误信息：{Message}", result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "轮播图图片上传过程中发生异常，文件名：{FileName}", imageFile?.FileName);

                return new ApiResult<string>
                {
                    code = ResultEnumCode.fails,
                    message = $"图片上传异常：{ex.Message}",
                    data = string.Empty
                };
            }
        }

        /// <summary>
        /// 修改轮播图信息
        /// </summary>
        /// <param name="command">修改命令</param>
        /// <returns>修改结果</returns>
        [HttpPost("update")]
        public async Task<ApiResult<bool>> UpdateCarousel([FromBody] UpdateCarouselCommand command)
        {
            try
            {
                _logger.LogInformation("开始修改轮播图信息，ID：{Id}，标题：{Title}", 
                    command.Id, command.CarouelChartTitle);

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("轮播图信息修改成功，ID：{Id}", command.Id);
                }
                else
                {
                    _logger.LogWarning("轮播图信息修改失败，ID：{Id}，错误信息：{Message}", 
                        command.Id, result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改轮播图信息过程中发生异常，ID：{Id}", command.Id);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"修改轮播图信息异常：{ex.Message}",
                    data = false
                };
            }
        }

        /// <summary>
        /// 批量逻辑删除轮播图信息
        /// </summary>
        /// <param name="command">批量删除命令</param>
        /// <returns>删除结果</returns>
        [HttpPost("batch-delete")]
        public async Task<ApiResult<bool>> BatchDeleteCarousel([FromBody] BatchDeleteCarouselCommand command)
        {
            try
            {
                _logger.LogInformation("开始批量逻辑删除轮播图，删除数量：{Count}，删除的ID：{Ids}", 
                    command.Ids?.Count ?? 0, string.Join(", ", command.Ids ?? new List<int>()));

                var result = await _mediator.Send(command);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("批量逻辑删除轮播图成功，删除数量：{Count}", command.Ids?.Count ?? 0);
                }
                else
                {
                    _logger.LogWarning("批量逻辑删除轮播图失败，错误信息：{Message}", result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量逻辑删除轮播图过程中发生异常，删除的ID：{Ids}", 
                    string.Join(", ", command.Ids ?? new List<int>()));

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"批量删除轮播图异常：{ex.Message}",
                    data = false
                };
            }
        }
    }
}